package com.m20studio.mop.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.m20studio.mop.xml.XMLFeed;

public class DBHelper{
	private DB data;

	public DBHelper(Context context){
		data = new DB(context);
	}

	public void save(XMLFeed feed) throws Exception{
		SQLiteDatabase db = data.getWritableDatabase();
		String sql = "insert into m20_mop ( title, hf, time, url) values(?, ?, ?, ?)";
		db.execSQL(sql, new Object[] { feed.getTitle(), feed.getHf(), feed.getTime(), feed.getURL() });
		db.close();
	}

	public List<XMLFeed> getListData(int offset, int maxResult){
		SQLiteDatabase db = data.getReadableDatabase();
		List<XMLFeed> lists = new ArrayList<XMLFeed>();

		String sql = "select * from m20_mop order by _id asc limit ? , ?";
		Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(offset),
				String.valueOf(maxResult) });
		
		while(cursor.moveToNext()){
			
			XMLFeed feed = new XMLFeed();
			
			int id = cursor.getInt(cursor.getColumnIndex("_id"));
			feed.setId(id);
			
			String title = cursor.getString(cursor.getColumnIndex("title"));
			feed.setTitle(title);
			
			String hf = cursor.getString(cursor.getColumnIndex("hf"));
			feed.setHf(hf);
			
			String time = cursor.getString(cursor.getColumnIndex("time"));
			feed.setTime(time);
			
			String url = cursor.getString(cursor.getColumnIndex("url"));
			feed.setURL(url);
			
			lists.add(feed);
		}
		
		cursor.close();
		db.close();
		
		return lists;

	}
		
	public void delete(int id)
	{
		SQLiteDatabase db = data.getWritableDatabase();
		db.execSQL("delete from m20_mop where _id = ?",
				new Object[] { String.valueOf(id) });
		db.close();
	}
	
	public void deleteAllData(){
		SQLiteDatabase db = data.getWritableDatabase(); 
		db.execSQL("delete from m20_mop");
		db.close();
	}
}
